package com.md.api.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kuaidi100.sdk.request.QueryTrackParam;
import com.kuaidi100.sdk.request.QueryTrackReq;
import com.md.api.common.utils.RedisUtil;
import com.md.api.common.utils.StringUtils;
import com.md.api.common.utils.TokenUtil;
import com.md.api.dao.*;
import com.md.api.entity.*;
import com.md.api.entity.dto.ComposeQueryDto;
import com.md.api.entity.dto.Express100DTO;
import com.md.api.entity.dto.SkuDetailDto;
import com.md.api.entity.enums.BizType;
import com.md.api.entity.enums.ProductType;
import com.md.api.entity.enums.SaleStatus;
import com.md.api.entity.util.Page;
import com.md.api.service.ShoppingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author liujie
 * @ClassName ProductServiceImpl
 **/

@Slf4j
@Service
public class ShoppingServiceImpl implements ShoppingService {

    @Resource
    UserMapper userMapper;
    @Resource
    ShoppingSpuTypeMapper spuTypeMapper;
    @Resource
    ShoppingDicMapper shoppingDicMapper;
    @Resource
    ShoppingSkuMapper shoppingSkuMapper;
    @Resource
    ShoppingSpuMapper shoppingSpuMapper;
    @Resource
    ShoppingAttributeMapper attributeMapper;
    @Resource
    ShoppingAttributeValueMapper attributeValueMapper;
    @Resource
    ShoppingSpuAttributeRelationMapper spuRelationMapper;
    @Resource
    ShoppingSkuAttributeRelationMapper skuRelationMapper;
    @Resource
    TokenUtil tokenUtil;
    @Resource
    RedisUtil redisUtil;
    @Resource
    ShoppingCartMapper shoppingCartMapper;

//    @Override
//    public HttpResult page( ComposeQueryDto qto) {
//        Page page = qto.getPage();
//        page.initPagingData(ShoppingSpu.class);
//        List<ShoppingSpu> list = shoppingSpuMapper.list(qto.getKeyword(),qto.getServiceType(),qto.getDrinkingType(),1);
//        page.setResult(list);
//        return new HttpResult(page);
//    }

    @Override
    public HttpResult page( HttpServletRequest request,ComposeQueryDto qto) {

        String userId = tokenUtil.getUserId(request);
//        if (StringUtils.isNotEmpty(userId)) {
//            UserInfo user = userMapper.getByUserId(userId);
//            log.info("user.getUserType():"+user.getUserType());
//            if (user.getUserType()==1){
                Page page = qto.getPage();
                page.initPagingData(ShoppingSku.class);
                List<ShoppingSku> list = shoppingSkuMapper.allList(qto.getKeyword(),qto.getShoppingType(),qto.getOrderType());
                page.setResult(list);
                return new HttpResult(page);
//            }else{
//                Page page = qto.getPage();
//                page.initPagingData(ShoppingSku.class);
//                List<ShoppingSku> list = shoppingSkuMapper.list(qto.getKeyword(),qto.getShoppingType(),qto.getOrderType());
//                page.setResult(list);
//                return new HttpResult(page);
//            }
//        }else{
//            Page page = qto.getPage();
//            page.initPagingData(ShoppingSku.class);
//            List<ShoppingSku> list = shoppingSkuMapper.list(qto.getKeyword(),qto.getShoppingType(),qto.getOrderType());
//            page.setResult(list);
//            return new HttpResult(page);
//        }
    }

    @Override
    public HttpResult recommend( ) {
        List<ShoppingSpu> list = shoppingSpuMapper.recommend();
        return new HttpResult(list);
    }

    @Override
    public HttpResult getNew( ) {
        List<ShoppingSpu> list = shoppingSpuMapper.getNew();
        return new HttpResult(list);
    }

    @Override
    public HttpResult spuTypePage( ComposeQueryDto qto) {
        Page page = qto.getPage();
        page.initPagingData(ShoppingSpuType.class);
        List<ShoppingSpuType> list = spuTypeMapper.selectAll();
        page.setResult(list);
        return new HttpResult(page);
    }

    @Override
    public HttpResult spuDetail( ShoppingSpu spuo) {

        //产品基本信息和共有属性
        ShoppingSpu spu =  shoppingSpuMapper.getBaseInfo(spuo.getSpuId());
        List<ShoppingSpuAttributeRelation> publicAttrResult = shoppingSpuMapper.getPublicAttr(spuo.getSpuId());
        if (!CollectionUtils.isEmpty(publicAttrResult)) {
            spu.setPublicAttributes(publicAttrResult);
        }
        List<ShoppingAttribute> privateAttrResult = shoppingSpuMapper.getPrivateAttr(spuo.getSpuId());
        if (!CollectionUtils.isEmpty(privateAttrResult)) {
            spu.setPrivateAttributes(privateAttrResult);
        }
        return new HttpResult(spu);
    }

    @Override
    public HttpResult skuDetail( HttpServletRequest request,SkuDetailDto dto) {
        ShoppingSku sku =  shoppingSpuMapper.skuDetail(dto.getSpuId(),dto.getAttributeValueIds());
        if (null==sku){
            return HttpResult.fail("未查询到相关详情！");
        }
        return new HttpResult(sku);
    }

    @Override
    public HttpResult attributeList(ShoppingAttribute attribute) {
        List<ShoppingAttribute> pdAttributes = attributeMapper.getByBizType(attribute.getBizType());
        return new HttpResult(pdAttributes);
    }

    @Override
    public HttpResult attributeTree(ShoppingAttribute attribute) {
        List<ShoppingAttribute> pdAttributes = attributeMapper.getByBizType(attribute.getBizType());
        List<Map<String,Object>> resultList = new ArrayList<>();
        for (ShoppingAttribute pdAttribute:pdAttributes){
            Map<String,Object> map = new HashMap<>();
            List<Map<String,Object>> valueList = new ArrayList<>();
            for (ShoppingAttributeValue attributeValue:pdAttribute.getAttributeValueList()){
                Map<String,Object> valueMap = new HashMap<>();
                valueMap.put("label",attributeValue.getAttributeValue());
                valueMap.put("value",attributeValue.getAttributeValueId());
                valueList.add(valueMap);
            }
            map.put("label",pdAttribute.getAttributeName());
            map.put("value",pdAttribute.getAttributeId());
            map.put("children",valueList);
            resultList.add(map);
        }
        return new HttpResult(resultList);
    }

    @Override
    public HttpResult skuUp(ShoppingSku sku) {
        ShoppingSku dbSku = shoppingSkuMapper.getBySkuId(sku.getSkuId());
        if (ProductType.GOODS.value()==dbSku.getType()) {
            if (null == dbSku.getStockCount()) {
                return HttpResult.fail("庫存量未設置！");
            }
            if (null == dbSku.getLockStockCount()) {
                return HttpResult.fail("最大庫存量未設置！");
            }
            if (null == dbSku.getOrginPrice()) {
                return HttpResult.fail("價格未設置！");
            }
        }
        shoppingSkuMapper.skuUpOrDown(sku.getSkuId(), SaleStatus.LISTING.value());
        //是否该商品下的所有产品都下架了
        Integer count = shoppingSpuMapper.listingSku(dbSku.getSpuId());
        ShoppingSpu spu = new ShoppingSpu();
        spu.setSpuId(dbSku.getSpuId());
        if (count>0){
            spu.setSaleStatus(1);
        }else{
            spu.setSaleStatus(-1);
        }
        shoppingSpuMapper.downOrUp(spu);
        return HttpResult.OK;
    }

    @Override
    public HttpResult skuDown(ShoppingSku sku) {
        shoppingSkuMapper.skuUpOrDown(sku.getSkuId(), SaleStatus.DELISTING.value());
        //是否该商品下的所有产品都下架了
        ShoppingSku dbSku = shoppingSkuMapper.getBySkuId(sku.getSkuId());
        Integer count = shoppingSpuMapper.listingSku(dbSku.getSpuId());
        ShoppingSpu spu = new ShoppingSpu();
        spu.setSpuId(dbSku.getSpuId());
        if (count>0){
            spu.setSaleStatus(1);
        }else{
            spu.setSaleStatus(-1);
        }
        shoppingSpuMapper.downOrUp(spu);
        return HttpResult.OK;
    }

    @Override
    public HttpResult updateSpuBase(ShoppingSpu spu) {
        shoppingSpuMapper.updateSpu(spu);
        return HttpResult.OK;
    }

    @Override
    public HttpResult updateSkuBase(ShoppingSku sku) {

        if (null!=sku.getStockCount()&&sku.getStockCount()<0){
            return HttpResult.fail("数量不能小于0");
        }
        if (null!=sku.getDiscountPrice()&&sku.getDiscountPrice()<=0){
            return HttpResult.fail("优惠价金额有误，请输入大于0的数字");
        }
        if (null!=sku.getOrginPrice()&&sku.getOrginPrice()<=0){
            return HttpResult.fail("原价金额有误，请输入大于0的数字");
        }
        shoppingSkuMapper.updateBase(sku);
        if (null!=sku.getStockCount()){
            String key = "sku_" + sku.getSkuId();
            redisUtil.set(key, sku.getStockCount());
        }
        return HttpResult.OK;
    }


    @Override
    public HttpResult newAttribute( ShoppingAttribute attribute) {
        String attributeId = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
        attribute.setAttributeId(attributeId);
        attributeMapper.insert(attribute);
        return HttpResult.OK;
    }



    @Override
    public HttpResult updateAttribute(ShoppingAttribute attribute) {
        attributeMapper.update(attribute);
        return HttpResult.OK;
    }

    @Override
    public HttpResult deleteAttribute(ShoppingAttribute attribute) {
        ShoppingSkuAttributeRelation byAttributeId = skuRelationMapper.getByAttributeId(attribute.getAttributeId());
        if (null!=byAttributeId){
            return HttpResult.fail("该属性已被使用");
        }
        attributeMapper.deleteByAttributeId(attribute.getAttributeId());
        return HttpResult.OK;
    }



    @Override
    public HttpResult deleteAttributeValue(ShoppingAttributeValue attributeValue) {
        ShoppingSkuAttributeRelation byAttributeId = skuRelationMapper.getByAttributeValueId(attributeValue.getAttributeValueId());
        if (null!=byAttributeId){
            return HttpResult.fail("该属性已被使用");
        }
        attributeValueMapper.deleteByAttributeValueId(attributeValue.getAttributeValueId());
        return HttpResult.OK;
    }

    @Override
    public HttpResult updateAttributeValue(ShoppingAttributeValue attributeValue) {
//        ShoppingSkuAttributeRelation byAttributeId = skuRelationMapper.getByAttributeValueId(attributeValue.getAttributeValueId());
//        if (null!=byAttributeId){
//            return HttpResult.fail("该属性已被使用");
//        }
        attributeValueMapper.update(attributeValue);
        return HttpResult.OK;
    }




    @Override
    public HttpResult attributeValueList(String attributeId) {
        List<ShoppingAttributeValue> pdAttributeValue = attributeValueMapper.getByAttributeId(attributeId);
        return new HttpResult(pdAttributeValue);
    }

    @Override
    public HttpResult newAttributeValue(ShoppingAttributeValue attributeValue) {
        ShoppingAttribute attribute = attributeMapper.getByAttributeId(attributeValue.getAttributeId());
        if (BizType.AI_TIMES.value()==attribute.getBizType()&&!attributeValue.getAttributeValue().contains("次")){
            return HttpResult.fail("虛擬產品AI次數屬性明細填寫錯誤，示例：50次");
        }
        if (BizType.FACE_TIMES.value()==attribute.getBizType()&&!attributeValue.getAttributeValue().contains("次")){
            return HttpResult.fail("虛擬產品掃臉取相次數屬性明細填寫錯誤，示例：50次");
        }
        if (BizType.STORAGE.value()==attribute.getBizType()
                &&!attributeValue.getAttributeValue().contains("GB/年")
                &&!attributeValue.getAttributeValue().contains("GB/月")){
            return HttpResult.fail("虛擬產品儲存空間屬性明細填寫錯誤，示例：50GB/年，10GB/月");
        }
        String attributeValueId = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
        attributeValue.setAttributeValueId(attributeValueId);
        attributeValueMapper.insert(attributeValue);
        return HttpResult.OK;
    }

    @Override
    public HttpResult deleteShoppingProduct(ShoppingSpu spu) {
        
        shoppingSpuMapper.deleteBySpuId(spu.getSpuId());
        shoppingSkuMapper.deleteBySpuId(spu.getSpuId());
        return HttpResult.OK;
    }

    @Transactional
    @Override
    public HttpResult newProduct(ShoppingSpu spu) throws Exception  {
        String spuId = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
        spu.setSpuId(spuId);
        shoppingSpuMapper.newSpu(spu);
        //添加共有属性
        if (!CollectionUtils.isEmpty(spu.getPublicAttributes())) {
            List<ShoppingSpuAttributeRelation> publicAttributeList = spu.getPublicAttributes();
            for (ShoppingSpuAttributeRelation attribute : publicAttributeList) {
                attribute.setSpuId(spuId);
                spuRelationMapper.insert(attribute);
            }
        }
        //添加私有属性
        if (!CollectionUtils.isEmpty(spu.getPrivateAttributes())) {
            List<ShoppingAttribute> privateAttributeList = spu.getPrivateAttributes();
            List<List<String>> valueList = new ArrayList<>();
            for (ShoppingAttribute value : privateAttributeList) {
                valueList.add(value.getAttributeValueIds());
            }
            List<String> combine = generateSkuCombine(valueList, 0, "", new ArrayList<>());
            List<ShoppingSku> newSkuList = new ArrayList<>();
            List<ShoppingSkuAttributeRelation> newSkuAttributeRelationList = new ArrayList<>();
            for (String skuAttribute : combine) {
                String skuId = UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
                List<String> attributeValueIds = StringUtils.toList(skuAttribute);
                for (String attributeValueId : attributeValueIds) {
                    ShoppingSkuAttributeRelation skuAttributeRelation = new ShoppingSkuAttributeRelation();
//                skuAttributeRelation.setAttributeId(attribute.getAttributeId());
                    skuAttributeRelation.setSpuId(spuId);
                    skuAttributeRelation.setSkuId(skuId);
                    skuAttributeRelation.setAttributeValueId(attributeValueId);
                    newSkuAttributeRelationList.add(skuAttributeRelation);
                }
                //初始化sku，后续单独修改每条sku的价格 图片 补充名称
                ShoppingSku sku = new ShoppingSku();
                String attributeValue = attributeValueMapper.getConcatValues(attributeValueIds);
                sku.setType(spu.getType());
                sku.setSpuId(spuId);
                sku.setSkuId(skuId);
                sku.setSkuName(spu.getProductName() + " " + attributeValue);
                sku.setSkuSpecs(attributeValue);
                sku.setSkuDescription(attributeValue);
                newSkuList.add(sku);
            }
            shoppingSkuMapper.insertBatch(newSkuList);
            skuRelationMapper.insertBatch(newSkuAttributeRelationList);
            //完善attribute_id
            skuRelationMapper.fullAttributeId(spuId);
        }
        return HttpResult.OK;
    }

    public static List<String> generateSkuCombine(List<List<String>> list, int index, String str, List<String> newObjs) {
        if (index == list.size()) {
            newObjs.add(str);
            return newObjs;
        }
        for (String dataStr : list.get(index)) {
            if (StringUtils.isBlank(str)) {
                generateSkuCombine(list, index + 1, str + dataStr, newObjs);
            } else {
                generateSkuCombine(list, index + 1, str + "," + dataStr, newObjs);
            }
        }
        return newObjs;
    }


    @Override
    public HttpResult addShoppingCart(HttpServletRequest request, ShoppingCart shoppingCart) {
        String userId = tokenUtil.getUserId(request);
//        String userId = request.getHeader("userId");
        shoppingCart.setUserId(userId);
        shoppingCartMapper.insert(shoppingCart);
        return HttpResult.OK;
    }


    @Override
    public HttpResult findLogistics(ComposeQueryDto queryDto) {

        Page page = queryDto.getPage();
        page.initPagingData(ShoppingDic.class);
        List<ShoppingDic> list = shoppingDicMapper.findLogistics(queryDto.getKeyword());
        page.setResult(list);
        return new HttpResult(page);
    }


    @Override
    public HttpResult onceShoppingSetting(ShoppingSku sku) {
        shoppingSpuMapper.onceShoppingSetting(sku);
        shoppingSpuMapper.setLowerPrice(sku.getSpuId());
        return HttpResult.OK;
    }
}
